/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.jitengine.expressions.parser;

import com.inspur.edp.web.common.utility.StringUtility;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description:
 *
 * @author Noah Guo
 * @date 2021/01/07
 */
/// <summary>
/// 表达式实体解析
/// </summary>
public class EntityExpressionParser {
    /// <summary>
    ///  表达式实体解析
    /// </summary>
    /// <param name="source"></param>
    /// <param name="entityName"></param>
    /// <returns></returns>
    public String Parse(String source, String entityName) {
        String parsedResult = source;
        // 解析表达式中对应的entity匹配
        Matcher matchedEntityExpression = ExpressionSourceEntityMatch(source, entityName);

        while (matchedEntityExpression.find()) {
            /// 表达式实体entity具体项匹配
            String matchedExpressionValue = matchedEntityExpression.group();
            String result = ExpressionSourceItemMatch(entityName, matchedExpressionValue);
            if (!StringUtility.isNullOrEmpty(result)) {
                parsedResult = parsedResult.replace(matchedExpressionValue, result);
            }
        }

        return parsedResult;
    }


    /// <summary>
    /// 表达式匹配
    /// </summary>
    /// <param name="entityName"></param>
    /// <param name="matchedExpression"></param>
    /// <param name="i"></param>
    private static String ExpressionSourceItemMatch(String entityName, String matchedExpressionValue) {
        String result = matchedExpressionValue;
        Matcher matchedItemExpression = ExpressionSourceItemRegex(entityName, matchedExpressionValue);
        if (matchedItemExpression.find()) {
            String matchedItemExpressionValue = matchedItemExpression.group();
            if (!StringUtility.isNullOrEmpty(matchedItemExpressionValue)) {
                String replacedMatchedValue = matchedItemExpressionValue
                        .replace(entityName, "ENTITY~")
                        .replace(".", "/")
                        .replace("'", "")
                        .replace("\"", "");
                if (!((replacedMatchedValue.startsWith("\"") && replacedMatchedValue.endsWith("\"")) ||
                        (replacedMatchedValue.startsWith("'") && replacedMatchedValue.endsWith("\"")))) {
                    replacedMatchedValue = "'{" + replacedMatchedValue + "}'";
                }

                result = result.replace(matchedItemExpressionValue, replacedMatchedValue);

                // 括号替换
                result = replaceKuoHao(result);

            }

        }
        return result;
    }

    private static Matcher ExpressionSourceItemRegex(String entityName, String matchedExpressionValue) {
        String strPattern = "[\\'\\\"]?\\s*" + entityName + "[\\.\\[\\]a-zA-Z0-9_]+\\s*[\\'\\\"]?";
        Pattern regexItem = Pattern.compile(strPattern, Pattern.COMMENTS);
        return regexItem.matcher(matchedExpressionValue);
    }

    /// <summary>
    /// 针对输入的数据源进行正则匹配
    /// 匹配实体参数
    ///
    /// </summary>
    /// <param name="source"></param>
    /// <param name="entityName"></param>
    /// <returns></returns>
    public static Matcher ExpressionSourceEntityMatch(String source, String entityName) {
        String strPattern = "ctx\\.[^\n\\(]+\\(\\s*\"?\\s*" + entityName + "[\\.\\[\\]a-zA-Z0-9_]+\\s*\"?\\s*\\)?";
        Pattern regex = Pattern.compile(strPattern, Pattern.COMMENTS);
        return regex.matcher(source);
    }

    public static String replaceKuoHao(String source) {
        if (StringUtility.isNullOrEmpty(source)) {
            return source;
        }
        String result = source;
        Matcher kuoHaoMatched = expressionKuoHaoReplace(source);
        while (kuoHaoMatched.find()) {
            String matchedValue = kuoHaoMatched.group();
            result = result.replace(matchedValue, "");
        }
        return result;
    }

    public static Matcher expressionKuoHaoReplace(String source) {
        String strPattern = "\\[\\d*\\]";
        Pattern regex = Pattern.compile(strPattern, Pattern.COMMENTS);
        return regex.matcher(source);
    }
}
